package com.hotelsystem.common.utils;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtil {
	private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
	private static final String DB_URL = "jdbc:mysql://localhost:3306/hotel";

	private static final String USER = "root";
	private static final String PASS = "hasee";
	
	private static ComboPooledDataSource dataSource;
	
	
	private static ThreadLocal<Connection> t1 = new ThreadLocal<Connection>();
	
	static {
		dataSource = new ComboPooledDataSource();
		try {
			dataSource.setDriverClass(JDBC_DRIVER);
			dataSource.setJdbcUrl(DB_URL);
			dataSource.setUser(USER);
			dataSource.setPassword(PASS);
		} catch (PropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static DataSource getDataSource(){
		return dataSource;
	}
	
	public static Connection getConnection(){
		Connection conn = null;
		try {
			conn = t1.get();
			if( null == conn ){
				conn = dataSource.getConnection();
				t1.set( conn  );
			}
			return conn;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static void beginTransaction(){
		Connection conn = null;
		 try {
			conn = t1.get();
			conn.setAutoCommit( false );
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void commitTransaction(){
		Connection conn = null;
		 try {
			 conn = t1.get();
			conn.commit();
			//t1.remove();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void rollbackTransaction(){
		Connection conn = null;
		 try {
			 conn = t1.get();
			conn.rollback();
			t1.remove();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void close( PreparedStatement ps){
		if( null != ps ){
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			Connection conn = t1.get();
			if( null != conn ){
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
